/**
 * @description 路由守卫，目前两种模式：all模式与intelligence模式
 */
import router from "./index";
import setting from "../config/setting.config";
import { useStore, useUserStore, useRouterStore } from "@/store";
import VabProgress from "nprogress";
import "nprogress/nprogress.css";

VabProgress.configure({
  easing: "ease",
  speed: 500,
  trickleSpeed: 200,
  showSpinner: false,
});

const { routesWhiteList,authentication,loginInterception,recordRoute } = setting;

router.beforeEach(async (to, from, next) => {
  VabProgress.start();
  const store = useStore();
  const useAdminStore = useUserStore();
  const routerStore = useRouterStore();

  let hasToken = store.getAccessToken;
  if (!loginInterception) hasToken = true;
  if (hasToken) {
    if (to.path === "/login") {
      next({ path: "/" });
    } else {
      const hasRoles = store.getAdmin;
      if (hasRoles) {
        next();
      } else {
        try {
          //           if (loginInterception) {
          //           await store.dispatch("user/getUserInfo");
          // } else {
          //           //loginInterception为false（关闭登录拦截时）时，创建虚拟角色
          await useAdminStore.setVirtualRoles();
          // }
          let accessRoutes = [];
          if (authentication === "intelligence") {
            accessRoutes = await routerStore.setRoutes();
          } else if (authentication === "all") {
            accessRoutes = await routerStore.setAllRoutes();
          }
          accessRoutes.forEach((item) => {
            router.addRoute(item);
          });
          next({ ...to, replace: true });
        } catch {
          await routerStore.resetAll();
          if (recordRoute) {
            next({
              path: "/login",
              query: { redirect: to.path },
              replace: true,
            });
          } else {
            next({ path: "/login", replace: true });
          }
        }
      }
    }
  } else {
    if (routesWhiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      if (recordRoute)
        next({ path: "/login", query: { redirect: to.path }, replace: true });
      else next({ path: "/login", replace: true });
    }
  }
});

router.afterEach((to) => {
  // document.title = "Error afterEach";
  VabProgress.done();
});
